package com.example.demo.Task;

import com.example.demo.domain.dao.HbutEmptyClassRoom;
import com.example.demo.domain.send.DingMessage;
import com.example.demo.service.EmptyClassRoomService;
import com.example.demo.service.SendDingMessageService;
import com.example.demo.utils.ParseUtil;
import com.google.gson.Gson;
import java.util.Arrays;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;

/**
 * 获取所有空教室的时间段并存入数据库
 *
 * @author lzq
 */
@Data
@Slf4j
public class GetClassRoomEmptyTimeThread implements Runnable {

    private EmptyClassRoomService emptyClassRoomService;
    private static Gson json = new Gson();
    private String classRoom;
    public GetClassRoomEmptyTimeThread(){}

    public GetClassRoomEmptyTimeThread(EmptyClassRoomService emptyClassRoomService, String classRoom) {
        this.emptyClassRoomService = emptyClassRoomService;
        this.classRoom = classRoom;
    }

    /**
     *  将教室空闲时间保存数据库
     */
    private void store(int [][][] classRoomEmptyTime){
        ArrayList<HbutEmptyClassRoom> result=new ArrayList<>(1000);
        int sum=0;
        for(int i=1;i<28;i++){
            for (int j=1;j<8;j++){
                for (int k=1;k<6;k++){
                    if(classRoomEmptyTime[i][j][k]==1){
                        result.add(new HbutEmptyClassRoom(Integer.parseInt(classRoom.substring(0,1)),i,j,k,classRoom));
                        sum++;
                    }
                }
            }
        }
        System.out.println(sum);
        if(sum>0){
            emptyClassRoomService.addEmptyClassRoom(result);
        }
    }


    @Override
    public void run() {
        try {
            int[][][] classRoomEmptyTime = ParseUtil.getClassRoomEmptyTime(classRoom);
            store(classRoomEmptyTime);
        } catch (Exception e) {
            log.error(classRoom+"-getEmptyClassRoom error");
            log.error("errorMessage:"+e.getMessage());
            log.error("stack:"+ Arrays.toString(e.getStackTrace()));
            SendDingMessageService.sendGetDataMessage(new DingMessage("爬取"+classRoom+"教室失败,errorMessage:"+e.getMessage()));
        }
    }

}
